import hmac
import hashlib
import base64
import json

def hmac_encode(plaintext, salt):
    key = salt.encode()
    message = plaintext.encode()
    h = hmac.new(key, message, hashlib.sha256).hexdigest()
    # 截取前22个字符
    return h[:22]

# 从JWT token中解析可能的盐值
def extract_jwt_parts(token):
    parts = token.split('.')
    results = []
    
    for part in parts:
        # 添加原始部分
        results.append(part)
        
        # 尝试解码
        try:
            # 处理可能的填充问题
            padding = len(part) % 4
            if padding:
                part += '=' * (4 - padding)
                
            decoded = base64.urlsafe_b64decode(part)
            try:
                # 尝试解析为JSON
                json_data = json.loads(decoded)
                # 将JSON中的每个值添加为可能的盐值
                for key, value in json_data.items():
                    if isinstance(value, str):
                        results.append(value)
            except:
                # 如果不是有效的JSON，则添加为字符串
                results.append(decoded.decode('utf-8', errors='ignore'))
        except:
            # 解码失败，跳过
            pass
            
    return results

# 已知的输入和输出
plaintext = "001671"
known_hash = "A9XGGbveFBdsQh0n4EXh"

# JWT token
jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEzMjk4LCJpc3MiOiJjZ2Jvc3MiLCJleHAiOjE3NTU3NDY5OTUsIm5iZiI6MTc1MzE1NDk5NSwiaWF0IjoxNzUzMTU0OTk1fQ.lZfw2ESYhSWwM0GTW6UdEhFdz31A75u3eAYqoT9SapA"
jwt_parts = extract_jwt_parts(jwt_token)

# 测试几个可能的盐值
salt_candidates = [
    "your_secret_salt",
    "cloudgame",
    "vmid",
    "cgboss",
    "vrviu",
    "yuntiancloud",
    "cloudsalt",
    "cloud_game_salt",
    "cg_salt",
    "vmid_salt",
    "cg_secret",
    "cgid_salt",
    # 从配置文件中可能的盐值
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", 
    "eyJ1c2VySWQiOjEzMjk4LCJpc3MiOiJjZ2Jvc3MiLCJleHAiOjE3NTU3NDY5OTUsIm5iZiI6MTc1MzE1NDk5NSwiaWF0IjoxNzUzMTU0OTk1fQ",
    "lZfw2ESYhSWwM0GTW6UdEhFdz31A75u3eAYqoT9SapA",
    # 从JWT token解析的值
    *jwt_parts,
    # 业务相关的值
    "13298",  # userId from JWT
    "cgboss",  # iss from JWT
    "1755746995",  # exp from JWT
    "1753154995",  # nbf and iat from JWT
    # 配置文件中的一些值
    "8565",  # EMC_ID
    "10125",  # biz_type
    "999",  # user_type
    # 用户ID相关值
    "001671",  # 原始值
    "1671",   # 去掉前导0
    # 其他可能性
    "api-bnd.yuntiancloud.com",
    "cgmgr.vrviu.com",
    "cgboss.yuntiancloud.com",
    # 混合值
    "vmid001671",
    "vmid_001671",
    "cgboss001671",
    "cgboss_001671",
    "yuntian001671",
    "yuntian_001671",
    # 尝试一些常用加密盐值
    "secret",
    "apikey",
    "apisalt",
    "secretkey",
    "hmackey",
    # 中文的可能性
    "云天云游戏",
    "云天",
    "云游戏",
    "虚拟机"
]

print(f"尝试查找可以将 '{plaintext}' 加密为 '{known_hash}' 的盐值...")
print(f"共测试 {len(salt_candidates)} 个候选盐值")

# 尝试常见盐值
for i, salt in enumerate(salt_candidates):
    result = hmac_encode(plaintext, salt)
    print(f"{i+1}. 盐值: '{salt}' -> 结果: '{result}'")
    
    if result == known_hash:
        print(f"\n找到匹配的盐值: '{salt}'")
        break

# 如果常见盐值都不匹配，尝试蛮力破解简单盐值
if all(hmac_encode(plaintext, salt) != known_hash for salt in salt_candidates):
    print("\n尝试一些简单盐值...")
    
    # 尝试简单数字和字符组合
    for i in range(1000):
        salt = str(i)
        result = hmac_encode(plaintext, salt)
        if result == known_hash:
            print(f"\n找到匹配的盐值: '{salt}'")
            break
            
        # 每测试100个值输出一次进度
        if i % 100 == 0:
            print(f"已尝试 {i} 个简单盐值")

    # 尝试云天ID相关的值
    for i in range(8000, 9000):
        salt = str(i)
        result = hmac_encode(plaintext, salt)
        if result == known_hash:
            print(f"\n找到匹配的盐值: '{salt}'")
            break
            
        # 每测试100个值输出一次进度
        if i % 100 == 0:
            print(f"已尝试 emc_id 相关盐值 {i}")

print("\n验证: ")
# 验证解密其他例子
other_examples = [
    ("558770", "c0Gkng2912yj1vRRtcho"),
    ("885864", "xy0367tAEAZEdHdf0kHj")
]

# 尝试找到正确的盐值并验证
found_salt = None
for salt in salt_candidates:
    if hmac_encode(plaintext, salt) == known_hash:
        found_salt = salt
        break

if found_salt:
    print(f"使用盐值 '{found_salt}':")
    for example_input, example_output in other_examples:
        result = hmac_encode(example_input, found_salt)
        print(f"  输入: '{example_input}' -> 期望: '{example_output}', 实际: '{result}'")
else:
    print("未找到匹配的盐值") 